package impl

import (
	"errors"
	"meituan/apps/admin/models"
	db2 "meituan/db"
	"meituan/utils/auth"
	"meituan/utils/password"
)

// UserServiceImpl 用户Service层实现
type UserServiceImpl struct {
}

// QueryOne 查询一个用户
func (u *UserServiceImpl) QueryOne(id int) (user *models.Users) {
	panic("implement me")
}

// Register 注册一个用户
func (u *UserServiceImpl) Register(users *models.Users) (err error) {
	db, _ := db2.NewDB()
	var exists int
	db.Model(new(models.Users)).Where("username = ?", users.Username).Count(&exists)
	if exists != 0 {
		return errors.New("重复的用户")
	}
	users.Password = password.Marshal(users.Password)
	db.Create(users)

	return nil
}

// Login 用户登陆
func (u *UserServiceImpl) Login(users *models.Users) (token string, err error) {
	token = "JOJO"
	subject := auth.NewSubject(auth.DefaultRealm{})
	info, err := subject.Login(users)
	if err != nil {
		return
	}

	token = info.GetToken()
	return
}

// NewUserServiceImpl 获取一个用户Service层实现
func NewUserServiceImpl() *UserServiceImpl {
	return new(UserServiceImpl)
}
